package com.itboye.ihomebank.activity.keytwo;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.bigkoo.pickerview.TimePickerView;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.RentInfoBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.MyGongJv;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.util.UIAlertViewTwo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

/**
 * 白马锁发送钥匙
 */
public class SendKeyActivity extends BaseOtherActivity implements Observer {
    View v_statusbar;
    ImageView send_key_finish;// 返回
    RelativeLayout send_key_xuanze;// 选择钥匙类型
    TextView send_key_xuan;// 钥匙类型
    LinearLayout send_key_kuang;// 选择框

    LinearLayout send_layout01;// 永久钥匙时候的界面
    EditText send_yaoshi, send_beizhu;// 永久钥匙时候的界面(住家账号,备注)
    TextView send_ok01;// 永久钥匙时候的界面(发送)

    LinearLayout send_layout02;// 期限钥匙时候的界面
    EditText send_yaoshi02, send_beizhu02;// 期限钥匙时候的界面(住家账号,备注)
    TextView send_start_time, send_stop_time;// 期限钥匙时候的界面(开始时间，结束时间)
    TextView send_ok02;// 期限钥匙时候的界面(发送)

    PopupWindow popupWindow;
    KeyTwoPresenter keyPresenter;
    private String lockId;
    private String uid;
    private String toUid;
    private String mark;

    long startT,endT;
    long currentTime;

    LinearLayout kaishi_time,jieshu_time;
    TextView kaishi_time_tv,jieshu_time_tv;
    private TimePickerView pvCustomTimeStart,pvCustomTimeEnd;
    long startDate;

    String phone="";//该锁绑定的房源的用户手机号
    String type="";//标志是什么类型的用户跳过来的，admin管理员（可以发租户钥匙和普通钥匙），rent租户（只能发租户用户钥匙）。
    String send_type="1";//发送的钥匙类型{管理员发送(1用户/2租户),租户发送(3租户用户)}

    long start,end;

    UIAlertViewTwo uiAlertViewTwo;
    int cz;
    @Override
    protected int layout_id() {
        return R.layout.activity_send_key_two;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        lockId = getIntent().getStringExtra("lockid");
        type = getIntent().getStringExtra("type");
        start= getIntent().getLongExtra("start",0);
        end= getIntent().getLongExtra("end",0);
        keyPresenter=new KeyTwoPresenter(this);

        if (type.equals("0")){
            uiAlertViewTwo=new UIAlertViewTwo(this,"租客管理员","普通用户","取消");
            uiAlertViewTwo.show();
            uiAlertViewTwo.setClicklistener(new UIAlertViewTwo.ClickListenerInterface() {
                @Override
                public void doOne() {
                    uiAlertViewTwo.dismiss();
//                    showProgressDialog("正在获取租户信息，请稍后......",false);
//                    keyPresenter.onRentInfo(uid,lockId);
                    send_layout01.setVisibility(View.GONE);
                    send_layout02.setVisibility(View.VISIBLE);
                    send_key_xuanze.setVisibility(View.GONE);
                    send_type="2";
                }

                @Override
                public void doTwo() {
                    uiAlertViewTwo.dismiss();
                    send_type="1";
                }

                @Override
                public void doThree() {
                    uiAlertViewTwo.dismiss();
                    send_type="1";
                }
            });

        }else{
            send_type="3";//租户只能给普通用户发租户钥匙
            send_key_xuan.setText("期限");
            send_layout01.setVisibility(View.GONE);
            send_layout02.setVisibility(View.VISIBLE);
            startT=start*1000;
            send_start_time.setText(TimesUtils.timeStamp2Date(start)+"");
            endT=end*1000;
            send_stop_time.setText(TimesUtils.timeStamp2Date(end)+"");
        }

        currentTime = System.currentTimeMillis();
        initTimePickerStart();
        initTimePickerEnd();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        switch (v.getId()) {
            case R.id.send_key_finish:
                finish();
                break;
            case R.id.send_key_xuan:
            case R.id.send_key_xuanze:
                PuPoWindow(v);
                break;
            case R.id.send_key_yongjiu:// 永久钥匙
                popupWindow.dismiss();
                send_key_xuan.setText("永久");
                send_layout01.setVisibility(View.VISIBLE);
                send_layout02.setVisibility(View.GONE);

                break;
            case R.id.send_key_qixian:// 期限钥匙
                popupWindow.dismiss();
                send_key_xuan.setText("期限");
                send_layout01.setVisibility(View.GONE);
                send_layout02.setVisibility(View.VISIBLE);
                break;
            case R.id.send_ok01:// 永久
                if(send_yaoshi.getText().toString().equals("")){
                    ByAlert.alert("请输入对方账号");
                    return;
                }
                if (send_yaoshi.getText().toString().trim().equals(phone)){
                    ByAlert.alert("不能给租客发送永久钥匙");
                    return;
                }
                if (type.equals("2")){
                    ByAlert.alert("租客不能发送永久钥匙");
                    return;
                }
                showProgressDialog("请稍后...", true);

                String touid = send_yaoshi.getText().toString();
                mark = send_beizhu.getText().toString();
                lockId = getIntent().getStringExtra("lockid");
                cz=1;
                String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid)){
                    keyPresenter.onSendKey(uid, touid, lockId, send_type,"0", "0", mark);

                }else {
                    keyPresenter.onSendKey(sid, touid, lockId, send_type,"0", "0", mark);
                }
                break;
            case R.id.send_ok02:
                if(send_yaoshi02.getText().toString().equals("")){
                    ByAlert.alert("请输入对方账号");
                    return;
                }
//                if (type.equals("0")){//管理员发送租户钥匙和普通钥匙
//                    if (send_yaoshi02.getText().toString().trim().equals(phone)){
//                        send_type="2";
//                    }else{
//                        send_type="1";
//                    }
//                }else{//租户只能给普通用户发租户钥匙
//                    send_type="3";
//                }

                if(!send_start_time.getText().toString().equals("")&&!send_stop_time.getText().toString().equals("")){
                    if (endT <= startT) {
                        ByAlert.alert("结束时间应该大于开始时间");
                        return;
                    }
                    if (currentTime > endT) {
                        ByAlert.alert("结束时间应该大于当前时间");
                        return;
                    }
                }
                showProgressDialog("请稍后...", true);
                mark = send_beizhu02.getText().toString();
                String toUid = send_yaoshi02.getText().toString();
                lockId = getIntent().getStringExtra("lockid");
                cz=2;
                String sid1=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid1)){
                    keyPresenter.onSendKey(uid, toUid, lockId, send_type,startT/1000+"", endT/1000+"", mark);
                }else {
                    keyPresenter.onSendKey(sid1, toUid, lockId, send_type,startT/1000+"", endT/1000+"", mark);

                }
                break;
            case R.id.kaishi_time:
            case R.id.kaishi_time_tv:
            case R.id.send_start_time:
                MyGongJv.yincang(v);
                pvCustomTimeStart.show();
                break;
            case R.id.jieshu_time:
            case R.id.jieshu_time_tv:
            case R.id.send_stop_time:
                MyGongJv.yincang(v);
                pvCustomTimeEnd.show();
                break;
            default:
                break;
        }
    }

    /**
     * 钥匙搜索切换框
     * @param v
     */
    private void PuPoWindow(View v) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.item_yaoshi_qiehuan, null);
        TextView send_key_yongjiu = (TextView) view
                .findViewById(R.id.send_key_yongjiu);
        TextView send_key_qixian = (TextView) view
                .findViewById(R.id.send_key_qixian);

        send_key_yongjiu.setOnClickListener(this);
        send_key_qixian.setOnClickListener(this);
        popupWindow = new PopupWindow(view, FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(v);
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getMsg().equals("未发现房源")){
                return;
            }
            if (entity.getEventType() == KeyTwoPresenter.rentInfo_success) {
                RentInfoBean bean= (RentInfoBean) entity.getData();
                if (bean!=null){//当该锁有绑定房源的时候，证明有租户，这个时候直接显示期限钥匙，把手机号码和租客的到期时间显示出来
                    phone=bean.getMobile();
                    send_key_xuan.setText("期限");
                    send_layout01.setVisibility(View.GONE);
                    send_layout02.setVisibility(View.VISIBLE);
                    startT=bean.getStart()*1000;
                    send_start_time.setText(TimesUtils.timeStamp2Date(bean.getStart())+"");
                    endT=bean.getEnd()*1000;
                    send_stop_time.setText(TimesUtils.timeStamp2Date(bean.getEnd())+"");
                    send_yaoshi02.setText(bean.getMobile());
                }

            } else if (entity.getEventType() == KeyTwoPresenter.rentInfo_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData()+"23");
                }

            }else
            if (entity.getEventType() == KeyTwoPresenter.sendKey_success) {
                ByAlert.alert(entity.getData());
                finish();
            } else if (entity.getEventType() == KeyTwoPresenter.sendKey_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }

            }else if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData(data1.getSid());
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }

    }

    private void toRefreshData(String sid) {
        if (cz==1){
            String touid = send_yaoshi.getText().toString();
            if ("".equals(sid)){
                keyPresenter.onSendKey(uid, touid, lockId, send_type,"0", "0", mark);
            }else {
                keyPresenter.onSendKey(sid, touid, lockId, send_type,"0", "0", mark);
            }
        }else if (cz==2){
            String toUid = send_yaoshi02.getText().toString();
            if ("".equals(sid)){
                keyPresenter.onSendKey(uid, toUid, lockId, send_type,startT/1000+"", endT/1000+"", mark);
            }else {
                keyPresenter.onSendKey(sid, toUid, lockId, send_type,startT/1000+"", endT/1000+"", mark);
            }
        }
    }

    private void initTimePickerStart() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTimeStart = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                send_start_time.setText(getTime(date));
                startT =  TimesUtils.getStringToDateTwo02(getTime(date));
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)

                .setType(new boolean[]{true, true, true, true, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();
    }
    private void initTimePickerEnd() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTimeEnd = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                send_stop_time.setText(getTime(date));
                endT =  TimesUtils.getStringToDateTwo02(getTime(date));
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)

                .setType(new boolean[]{true, true, true, true, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();
    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        return format.format(date);
    }
}
